"""
File: utils.py
Author: ershixiong
Date: 2023/12/25
describe:

"""
import json
import os

import jsonschema
import yaml
from genson import SchemaBuilder


class Utils:

    @classmethod
    def get_yaml_data(cls, path):
        """
        path 相对路径
        :param path:
        :return:
        """
        file_path = cls.join_path(path)
        with open(file_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)

    @classmethod
    def get_application_secret(cls, myenv, name, path):
        """
        根据不同环境，不同的应用，返回文件中对应应用的secret
        :param myenv:  环境
        :param name: 应用名称
        :param path: 相对路径
        :return:
        """
        yaml_data = cls.get_yaml_data(path).get(myenv).get(name)
        return yaml_data

    @classmethod
    def get_root_dir(cls):
        """
        :return: 根目录路径
        """
        root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        return root_dir

    @classmethod
    def join_path(cls, path):
        """
        :param path: 相对路径
        :return: 绝对路径
        """
        abs_path = os.sep.join([cls.get_root_dir(), path])
        return abs_path

    @classmethod
    def generate_schema(cls, obj, path):
        """
        将obj对象，以schema的格式写入到json文件
        :param obj:
        :param path:相对路径
        :return:
        """

        builder = SchemaBuilder()
        # 将 Python 对象（例如字典、列表等）添加到 SchemaBuilder 中
        builder.add_object(obj)
        # 生成 json schema
        schema_content = builder.to_schema()

        # 写入json文件
        path = cls.join_path(path)
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(schema_content, f)

    @classmethod
    def schema_validate(cls, obj, path):
        """
        :param obj:
        :param path: 相对路径
        :return:
        """
        try:
            if not os.path.exists(cls.join_path(path)):
                cls.generate_schema(obj, path)

            schema_content = cls.get_json_data(path)
            jsonschema.validate(instance=obj, schema=schema_content)

            # 不抛出异常说明校验成功，将最新的数据写入
            cls.generate_schema(obj, path)
            return True
        except Exception as e:
            print(f'schema校验失败====== 》{e}')
            return False

    @classmethod
    def get_json_data(cls, path):
        """
        :param path: 相对路径
        :return:
        """
        path = cls.join_path(path)
        with open(path, 'r', encoding='utf-8') as f:
            return json.load(f)
